package com.example.isoftservice.shiro;

import com.example.isoftservice.pojos.User;
import com.example.isoftservice.service.UserService;
import com.example.isoftservice.shiro.token.JwtToken;
import com.example.isoftservice.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.val;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
public class UserRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Object principal = principals.getPrimaryPrincipal();            //获取登录的用户pojo对象
        User user = (User)principal;
        Integer auth = user.getRoleId();
        System.out.println("AuthorizationInfo principal=" + principal + " user.getRoleId()=" + user.getRoleId());
        if(user != null) {
            switch (auth) {
                case 0:
                    info.addRole("0");//0为超级管理员权限
                    break;
                case 1:
                    info.addRole("1");//1为运营人员权限
                    break;
                case 2:
                    info.addRole("2");//2为经销账户权限
                    break;

            }

        }


        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        User user = null;
        // 把AuthenticationToken实质为UsernamePasswordToken，直接转换即可
        JwtToken jwtToken = (JwtToken) token;
        String jwt = (String) jwtToken.getPrincipal();
        Claims claims = JwtUtils.parseJWT(jwt);
        String username = claims.getId();
        user = userService.getUser(username);          // 通过service查询用户名是否存在
        if (user == null)
            throw new UnknownAccountException("用户不存在！");
        System.out.println("doGetAuthenticationInfo username=" + user.getUsername());
        System.out.println("doGetAuthenticationInfo password=" + user.getPassword());

        //  spring_database.xml文件中已经对此UserRealm bean对象设置了加密方式和次数，固这里无需重复配置，如果xml文件中没有配置，则需要代码配置
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//        hashedCredentialsMatcher.setHashAlgorithmName("MD5");                      // 加密方式，与注册一致
//        hashedCredentialsMatcher.setHashIterations(11);                            // 加密次数，与注册一致
//        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);           // true是默认值，代表16机制值，如果设置false则为base64
//        setCredentialsMatcher(hashedCredentialsMatcher);                           // 保存加密设置
//        ByteSource credentialsSalt = ByteSource.Util.bytes("10086");    // 以username为加密盐值
//        String realmName = getName();                                              // 当前realm对象的name，调用父类的getName()方法即可
//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, user.getPassword(), credentialsSalt, realmName);
        // 在没有加盐的情况下，三个参数就可以进行初步的简单认证信息对象的包装
//        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getSimpleName());
        return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
    }
}

